using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

namespace MobileMedia
{
    /// <summary>
    /// 用于捕捉当前区域的渲染图像
    /// </summary>
    public class CaptureImageComponent : MonoBehaviour
    {
        public RectTransform leftBottom;
        public RectTransform rightTop;
        
        public void Capture(Action<Texture2D> action)
        {
            StartCoroutine(CaptureImage(action));
        }

        IEnumerator CaptureImage(Action<Texture2D> action)
        {
            yield return new WaitForEndOfFrame();
            try
            {
                var cameraObj = GameObject.Find("UIRoot/UICamera");

                Camera uiCamera = null;
                if (cameraObj)
                {
                    uiCamera = cameraObj.GetComponent<Camera>();
                }

                if (cameraObj)
                {
                    Vector2 lb = RectTransformUtility.WorldToScreenPoint(uiCamera, leftBottom.position);
                    Vector2 rt = RectTransformUtility.WorldToScreenPoint(uiCamera, rightTop.position);

                    int w = (int)(rt.x - lb.x);
                    int h = (int)(rt.y - lb.y);

                    Texture2D texture = new Texture2D(w, h, TextureFormat.RGB24, false);
                    Rect rect = new Rect(lb.x, lb.y, w, h);

                    texture.ReadPixels(rect, 0, 0, false);
                    texture.Apply();

                    action?.Invoke(texture);
                }
                else
                {
                    action?.Invoke(null);
                }
            }
            catch (Exception e)
            {
                action?.Invoke(null);
            }
            
        }
        
    }
}